package org.zhouhe.web.util;

import java.util.Date;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.zhouhe.common.EnumDateFormater;

public class ParameterUtils {
	private static Pattern patternHump = Pattern.compile("(_\\w)\\w?");
	public static <T> T fill(HttpServletRequest request, T bean){
		try {
			MutablePropertyValues pvs = new MutablePropertyValues();
			Enumeration<String> e = request.getParameterNames();
			while(e.hasMoreElements()){
				String varName = e.nextElement();
				String varVal = request.getParameter(varName);
				pvs.add(varName, varVal);
				pvs.add(prop2Hump(varName), varVal);
			}
			WebDataBinder db = new WebDataBinder(bean);
			db.registerCustomEditor(Date.class, new CustomDateEditor(new EnumDateFormater(), true));
			db.bind(pvs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bean;
	}
	
	/**
	 * 将属性名称转为驼峰式名称
	 * @param propName
	 * @return
	 */
	private static String prop2Hump(String propName) {
		propName = propName.toLowerCase();
		Matcher matcher = patternHump.matcher(propName);
		while (matcher.find()) {
			String value = matcher.group(1);
			String upCaseValue = value.replaceAll("_", "").toUpperCase();
			propName = propName.replaceFirst(value, upCaseValue);
		}
		return propName;
	}
}
